﻿#include "MainWindow.h"

#include <QDebug>
#include <QtConcurrent>

#include "./ui_MainWindow.h"
#include "TcpClient_T.h"
#include "TcpServer_T.h"

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent),
      ui(new Ui::MainWindow) {
  ui->setupUi(this);
}

MainWindow::~MainWindow() {
  delete ui;
}

// 用于新链接的socket收到信息时，进行处理的逻辑函数
void MainWindow::dealRead(const QByteArray &arg) {
  // static int num{0};
  // qDebug() << num++ << "receive:" << arg.size();
  //  static int num{0};
  //  QtConcurrent::run([=] {
  //    for (int i{0}; i != 10; ++i) {
  //      QByteArray msg{QString{"%1:%2"}.arg(num++).arg("world").toUtf8()};
  //      client_->write("world");
  //    }
  //  });
}

void MainWindow::on_btnTest0_clicked() {
  // 初始化 server
    ZTcp::TcpServer_T *server{new ZTcp::TcpServer_T{this}};
    // 监听地址、端口
    server->listen(QHostAddress::Any, 9966);
    // 当有新的请求连接时,触发sigNewClient信号
    connect(server, &ZTcp::TcpServer_T::sigNewClient, [=](ZTcp::TcpClient_T *client) {
      qDebug() << client->peerAddress() << client->peerPort();
      qDebug() << client->localAddress() << client->localPort();
      // 可以记录下来，在其他多线程中调用
      client_ = client;
      // 使用read注册回调函数dealRead
      client_->read([this](auto &&arg) { dealRead(std::forward<decltype(arg)>(arg)); });
    });

//  QTcpServer *server{new QTcpServer{this}};
//  server->listen(QHostAddress::Any, 9966);
//  connect(server, &QTcpServer::newConnection, [=] {
//    while (server->hasPendingConnections()) {
//      auto client = server->nextPendingConnection();
//      connect(client, &QTcpSocket::readyRead, [=] {
//        auto data{client->readAll()};
//      });
//    }
//  });
}

void MainWindow::on_btnTest1_clicked() {
  static int num{1};
  client_->write(QString::number(num).toUtf8());
}

void MainWindow::on_btnTest2_clicked() {
}

void MainWindow::on_btnTest3_clicked() {
}
